function StringBuffer() { this.buffer = []; }
StringBuffer.prototype.append = function (data) {
    this.buffer.push(data);
    return this;
}

StringBuffer.prototype.toString = function () {
    return this.buffer.join("");
}

var ilcMatches; /*store all the matches*/
var poolType = "HAD";
var pagePools = ["had", "chl", "hil", "fts", "nts", "ets"];
var leagueCode = "ALL";
var hasChannel = "ALL";
var isLiveCast = "ALL";
var hasInplayPool = "ALL";
var filteredMatches = new Array(); /*store all the filtered matches,and get the paging data from the array*/
var checkBoxArr = new Array();
var definedPoolArr = new Array();
var selectionCheckBox = new Array();
var isShowSelected = false;
var tips;
var timers = {};
var matchLineStyle = "";
var multipleLinePoolIds = [];
var lineRowCount = [];
var showHideBtn = [1, 1];

var oldMainline = [];
var oldOdds = [];
var timeoutObj = [];
var timeoutDT = [];
var simpleMatchList = [];

function initialize() {
    document.getElementById("selOddsType").options.length = 0;
    for (var i = 0; i < ilcPagePoolsOrder.length; i++) {
        var pool = pools[ilcPagePoolsOrder[i]];
        document.getElementById("selOddsType")[i] = new Option(pool.name, pool.value);
    }
    document.getElementById("selOddsType").value = pools[ilcPagePoolsOrder[0]].value;

    if (!checkHasMatches()) {
        setPageInfo(false);
    } else {
        setPageInfo(true);
        poolType = $("#selOddsType").val().toUpperCase();
        updateSimpleMatchList();
        render();
        updateAllMatchesTime();
        updatePerformTvVisibility();

        if (enableSelectLeague) {
            $(".selLeague").eq(0).show();
        } else {
            $(".selLeague").eq(0).hide();
        }
    }
}

//display matches,oddsType:HAD,HIL,CHL,FTS/NTS
function render() {
    $("#divLoading").show();

    closeEventWindow();
    //initialize the curPage
    // curPage = 1;

    definedPoolArr = new Array();
    if (enableSelectLeague) {
        setLeagues(ilcMatches, leagueCode);
    }

    //get the filtered matches
    filteredMatches = filterMatches(ilcMatches, leagueCode, poolType, hasChannel, isLiveCast, hasInplayPool);
    //display the matches
    var $obj = $("#tbMatches");
    $obj.empty();
    showHideBtn = [1, 1];
    var displayedMatches = getPagedMatches(filteredMatches, curPage, pageSize);
    resetMultipleLine();
    setLineCount(displayedMatches, poolType);
    $obj.html(drawMatchesHtml(displayedMatches, poolType));
    //add betline
    resetBetLineArray();
    createBetLinesForDisplayMatches(displayedMatches, poolType);
    //display the pagers
    $("#divPager").html(drawPagerHtml(pageSize, filteredMatches.matchesCount, curPage, buttonCount));
    $("#divPager").show();

    $("#divLoading").hide();
}

//re-render the display, oddsType:HAD,HIL,CHL,FTS/NTS
function reRender() {
    //if event window is open, display the event window
    var mID;
    if ($("#divDetails").length > 0) {
        mID = $("#divDetails").find("input[type=hidden]").eq(0).val();
        closeEventWindow();
    }
    //display the matches
    var $obj = $("#tbMatches");
    $obj.empty();
    showHideBtn = [1, 1];

    filteredMatches = filterMatches(ilcMatches, leagueCode, poolType, hasChannel, isLiveCast, hasInplayPool);

    //after refresh,the curPage maybe > pages
    var pages = filteredMatches.matchesCount % pageSize == 0 ? Math.floor(filteredMatches.matchesCount / pageSize) : Math.floor(filteredMatches.matchesCount / pageSize) + 1;
    if (curPage > pages) {
        curPage = (pages > 0 ? pages : 1);
    }
    var displayedMatches = getPagedMatches(filteredMatches, curPage, pageSize);
    setLineCount(displayedMatches, poolType);
    $obj.html(drawMatchesHtml(displayedMatches, poolType));

    if (enableSelectLeague) {
        setLeagues(ilcMatches, leagueCode);
    }

    //open the event window if the event window is open before render
    if (mID != null) {
        if ($("#rmid" + mID).length > 0) {
            var obj = $("#rmid" + mID).find(".cscore").eq(0);
            var oType = poolType;
            openEventWindow(obj, mID, oType);
        }
    }
    //add betline
    resetBetLineArray();
    createBetLinesForDisplayMatches(displayedMatches, poolType);

    //display the pagers
    $("#divPager").html(drawPagerHtml(pageSize, filteredMatches.matchesCount, curPage, buttonCount));
}

//filter matches by poolType,oddsType:HAD,HIL,CHL,FTS/NTS
function filterByOddsType(oddsType) {
    $("#divLoading").show();
    selectionCheckBox = [];
    oldOdds = [];
    timeoutObj = [];
    timeoutDT = [];
    poolType = oddsType.toUpperCase();
    hasChannel = "ALL";
    isLiveCast = "ALL";
    hasInplayPool = "ALL";
    curPage = 1;
    render();
    closeEventWindow();
}

//filter matches by league
function filterByLeague(lgCode) {
    $("#divLoading").show();
    selectionCheckBox = [];
    leagueCode = lgCode;
    hasChannel = "ALL";
    isLiveCast = "ALL";
    curPage = 1;
    render();
    closeEventWindow();
}

//filter matches,oddsType:HAD,HIL,CHL,FTS/NTS

function filterMatches(matchesArr, leagueCode, oddsType, hasChannel, isLiveCast, hasInplayPool) {
    if (matchesArr == null) return;

    var arr = new Array();
    arr.matchesCount = 0;
    for (var i = 0; i < matchesArr.length; i++) {
        var obj = {};
        obj.name = matchesArr[i].name;
        obj.matches = new Array();
        matchesArr[i].matches = matchesArr[i].matches.sort(sort_by2(['matchTime', 'matchDate', 'matchNum'], [false, false, false], [null, trimMatchDate, parseInt]));
        for (var j = 0; j < getMatchLength(matchesArr[i]) ; j++) {
            var m = new Match(matchesArr[i].matches[j]);
            if ($.isNullOrEmpty(m.matchIDinofficial)) continue;

            if (isShowSelected && hasAnyCheckboxSelected() && !checkBoxArr[m.matchIDinofficial]) continue;

            if (leagueCode.toLowerCase() != "all") {
                if (leagueCode.toLowerCase() == "others") {
                    if (m.league.leagueShortName != "CLB" && m.league.leagueShortName != "CUP" && m.league.leagueShortName != "INT") {
                        continue;
                    }
                } else if (m.league.leagueShortName != leagueCode) {
                    continue;
                }
            }
            var pool = getPool(m, oddsType);
            if (pool == null || pool.POOLSTATUS == '') {
                continue;
            } else {
                if (checkIsRefundPool(pool.POOLSTATUS)) {
                    continue;
                }
            }

            if (checkIsVoidMatch(m.matchStatus)) {
                continue;
            }
            if (hasChannel.toLowerCase() != "all") {
                var betSlip = top.document.getElementById('betSlipFrame');
                var needWebTVCheck = checkIsLogin() && betSlip && betSlip.contentWindow.GetDataStore('football_live_ind') == "Y";
                if (hasChannel.toLowerCase() == "yes") {
                    if (needWebTVCheck && hasWebTV(m.matchID)) { // not filter out
                    }
                    else if (m.channel != null && m.channel != undefined && m.channel.length > 0) { // not filter out
                    }
                    else {
                        continue;
                    }
                }
            }
            if (isLiveCast.toLowerCase() != "all") {
                var tmp = isLiveCast.toLowerCase() == "yes";
                if (getBetRadarId(m.matchID)=='') {
                    continue;
                }
            }
            if (hasInplayPool.toLowerCase() != "all") {
                // check all pools - pagePools
                var findInplayPool = false;
                for (var ppi = 0; ppi < pagePools.length; ppi++) {
                    if (m[pagePools[ppi] + "odds"] != undefined && m[pagePools[ppi] + "odds"] != null) {
                        if (m[pagePools[ppi] + "odds"].INPLAY == hasInplayPool) {
                            findInplayPool = true;
                        }
                    }
                }
                if (!findInplayPool) {
                    continue;
                }
            }
            obj.matches.push(m);
        }
        arr.push(obj);
        arr.matchesCount = arr.matchesCount + getMatchLength(obj);
    }
    return arr;
}


//set the header of the table,oddsType:HAD,HIL,CHL,FTS/NTS
function setHeader(oddsType) {
    oddsType = oddsType.toUpperCase();
    var oddsClass = "codds-had";
    var colspan = 3;

    if (oddsType == "HAD") {
        $("#spCol1").html(GetGlobalResources("HomeTeamWin", "js"));
        $("#spCol2").html(GetGlobalResources("DRAW", "js"));
        $("#spCol3").html(GetGlobalResources("AwayTeamWin", "js"));
        colspan = 3;
    } else if (oddsType == "HIL") {
        $("#spCol1").html(GetGlobalResources("Line", "js"));
        $("#spCol2").html(GetGlobalResources("Hight", "js"));
        $("#spCol3").html(GetGlobalResources("Low", "js"));
        oddsClass = "codds-hil";
        colspan = 3;
    } else if (oddsType == "CHL") {
        $("#spCol1").html(GetGlobalResources("CornerLine", "js"));
        $("#spCol2").html(GetGlobalResources("Hight", "js"));
        $("#spCol3").html(GetGlobalResources("Low", "js"));
        oddsClass = "codds-chl";
        colspan = 3;
    } else if (oddsType == "FTS/NTS") {
        $("#spCol1").html(GetGlobalResources("HomeTeam", "js"));
        $("#spCol2").html(GetGlobalResources("NoGoal", "js"));
        $("#spCol3").html(GetGlobalResources("AwayTeam", "js"));
        oddsClass = "codds-nts";
        colspan = 4;
    }
    document.getElementById("tdSelect").colSpan = colspan;

    $("#spCol1").parent().removeClass();
    $("#spCol2").parent().removeClass();
    $("#spCol3").parent().removeClass();
    $("#spCol1").parent().addClass(oddsClass);
    $("#spCol2").parent().addClass(oddsClass);
    $("#spCol3").parent().addClass(oddsClass);
}

//get the html of matches,oddsType:HAD,HIL,CHL,FTS/NTS
function drawMatchesHtml(matchesArr, oddsType) {
    var sb = new StringBuffer();
    var colspan = 15;
    oddsType = oddsType.toUpperCase();
    if (oddsType == "CHL") {
        colspan = 17;
        $("td.ccorner").show();
    } else {
        if (oddsType == "HIL")
            colspan = 16;
        $("td.ccorner").hide();
    }
    if (oddsType == "FTS/NTS") {
        colspan = 16;
        $("td.cgoal").show();
    } else {
        $("td.cgoal").hide();
    }

    for (var i = 0; i < matchesArr.length; i++) {
        if (getMatchLength(matchesArr[i]) > 0) {
            sb.append("<tr id=\"tgCou" + i + "\" class=\"rchead rTopBorder\">");
            sb.append("<td class=\"tgCoupon whiteBottomBorder\" onclick=\"tgILC(" + i + ");");
            sb.append("\" colspan=\"" + colspan + "\">");
            sb.append("<span id=\"tgCouBtn" + i + "\" class=\"spBtnMinus\"></span>");
            sb.append(GetGlobalResources(matchesArr[i].name == "ActiveMatches" ? "OtherMatches" : matchesArr[i].name, "js"));

            var hasMultipleLine = hasAnyMultipleLineMatch(matchesArr[i].matches, oddsType);
            if (hasMultipleLine) {
                sb.append("<span id=\"tgAllMLBtn_" + i + "\" style=\"float:right;\" onclick=\"toggleAllMLDisplay(event," + i + ",'" + oddsType + "');\">");
                if (multipleLinePoolIds[i + "_ALL"] == 1)
                    sb.append(GetGlobalResources("CollapseAll", "js") + "<span class=\"spBtnMinus\"></span></span>");
                else
                    sb.append(GetGlobalResources("ExpandAll", "js") + "<span class=\"spBtnPlus\"></span></span>");
            }
            sb.append("</td>");
            sb.append("</tr>");
            for (var j = 0; j < getMatchLength(matchesArr[i]) ; j++) {
                var m = matchesArr[i].matches[j];
                matchLineStyle = "rAlt" + ((j + 1) % 2) + " tgCou" + (i + 1) + " rcont";
                sb.append(drawHtmlOfMatch(i, m, oddsType, matchLineStyle));
            }

            showHeaderIcons();
        }
    }
    return sb.toString();
}

function resetMultipleLine() {
    multipleLinePoolIds = [];
    multipleLinePoolIds["0_ALL"] = 0;
    multipleLinePoolIds["1_ALL"] = 0;
}

function setLineCount(matchesArr, oddsType) {
    lineRowCount = [];
    for (var i = 0; i < matchesArr.length; i++) {
        for (var j = 0; j < getMatchLength(matchesArr[i]) ; j++) {
            var m = matchesArr[i].matches[j];
            var pool = getPool(m, oddsType);
            if (oddsType == "HIL" || oddsType == "CHL") {
                lineRowCount[i + '_' + m.matchIDinofficial] = pool.LINELIST.length;
            } else {
                lineRowCount[i + '_' + m.matchIDinofficial] = 1;
            }
        }
    }
}

function hasAnyMultipleLineMatch(matches, oddsType) {
    if (oddsType == "CHL" || oddsType == "HIL") {
        for (var index in matches) {
            if (isMultipleLineMatch(matches[index], oddsType))
                return true;
        }
    }
    return false;
}

function isMultipleLineMatch(match, oddsType) {
    if (oddsType == "CHL" || oddsType == "HIL") {
        var pool = getPool(match, oddsType);
        if (pool.LINELIST.length > 1)
            return true;
    }
    return false;
}


function updateCBSelect(obj, mId) {
    checkBoxArr[mId] = obj.checked;
}

function hasAnyCheckboxSelected() {
    for (var b in checkBoxArr) {
        if (checkBoxArr[b] == true)
            return true;
    }
    return false;
}

//get the html of match,oddsType:HAD,HIL,CHL,FTS/NTS
function drawHtmlOfMatch(coupon, m, oddsType, matchLineStyle) {
    var sb = new StringBuffer();
    definedPoolArr[m.matchIDinofficial + oddsType] = 1;
    var pool = getPool(m, oddsType);
    sb.append(drawNoramlOddsRow(coupon, m, oddsType, pool, matchLineStyle));
    return sb.toString();
}

function drawNoramlOddsRow(coupon, m, oddsType, pool, matchLineStyle) {
    var sb = new StringBuffer();

    //checkbox
    sb.append("<tr class=\"" + matchLineStyle + "\" id=\"rmid" + m.matchIDinofficial + "\">");
    sb.append("<td class=\"cselect\"><input type=\"checkbox\" value=\"" + m.matchIDinofficial + "\"");
    sb.append(checkBoxArr[m.matchIDinofficial] == true ? " checked " : "");
    sb.append(" onclick=\"updateCBSelect(this, '" + m.matchIDinofficial + "');\"/>");
    sb.append("<input type=\"hidden\" id=\"" + m.matchIDinofficial + "_delay\" value=\"" + (pool ? pool.inplaydelay : "false") + "\" />");
    sb.append("<input type=\"hidden\" id=\"" + m.matchIDinofficial + "_isMatchOfDay\" value=\"" + m.isMatchOfDay + "\" />");
    sb.append("<input type=\"hidden\" id=\"" + m.matchIDinofficial + "_esst\" value=\"" + m.esst + "\" />");
    sb.append("<input type=\"hidden\" id=\"" + m.matchIDinofficial + "_matchStatus\" value=\"" + m.matchStatus + "\" />");
    var matchStage = (m.liveEvent != null) ? m.liveEvent.matchstate : '';
    if (m.hasETSPool || matchStage == "FirstExtraTime" || matchStage == "ExtraHalfTime" || matchStage == "SecondExtraTime") {
        matchStage = "extratime";
    }
    sb.append("<input type=\"hidden\" id=\"hsst" + m.matchIDinofficial + "\" value=\"" + matchStage + "\" />");
    if (oddsType == "FTS/NTS") {
        sb.append("<input type=\"hidden\" id=\"" + m.matchIDinofficial + "_NTS_isETS\" value=\"" + !(m.etsodds == undefined && m.etsodds == null) + "\" />");
    }
    sb.append("</td>");
    //match no
    sb.append("<td class=\"cday\">");
    sb.append("<span id=\"" + m.matchIDinofficial + "_matchNum\">");
    sb.append(getMatchNum(m, oddsType));
    sb.append("</span></td>");
    //esst
    sb.append("<td class=\"cesst\"><span id=\"" + m.matchIDinofficial + "_status\">");
    if (m.liveEvent != null && (m.liveEvent.matchstate.indexOf("Delayed") >= 0
          || m.liveEvent.matchstate.indexOf("Interrupted") >= 0
          || m.liveEvent.matchstate.indexOf("Suspended") >= 0)) {
        sb.append("-");
    }
    else if (m.IsMatchKickOff()) {
        sb.append(formatStatus(m));
    } else if (!$.isNullOrEmpty(m.matchTime)) {
        sb.append(formatEsstStr(m.matchTime, false));
    }
    sb.append("</span></td>");
    //team
    sb.append(getTeamStr(m));
    //score

    sb.append("<td class=\"cscore redColor\">");
    if (m.liveEvent == null || m.liveEvent.matchstate==null
        || m.liveEvent.matchstate.indexOf("Delayed") >=0
        || m.liveEvent.matchstate.indexOf("Interrupted") >= 0
        || m.liveEvent.matchstate.indexOf("Suspended") >= 0) {
        sb.append("<span class=\"pointer\" id=\"" + m.matchIDinofficial + "_score\">");
        sb.append("-");
        sb.append("</span>");
    }
    else if (m.IsMatchKickOff() && !isNonInplayAndNoLiveInfoMatch(m)) {
        sb.append("<span class=\"pointer\" id=\"" + m.matchIDinofficial + "_score\"");
        if (!m.isEmergency) {
            sb.append(" onclick=\"openEventWindow(this,'" + m.matchIDinofficial + "','" + oddsType + "');\"");
        }
        sb.append(">");
        if (m.livescore != null) { // show live score if available
            sb.append(m.livescore.home + ':' + m.livescore.away);
        }
        else if ( m.inplayPools.length > 0 ) { // only show SBC score for in-play match
            sb.append(m.ipinfo[2].replace(/\s/g, ''));
        }
        else {
            sb.append("-");
        }
        sb.append("</span>");
    } else {
        sb.append("<span class=\"pointer\" id=\"" + m.matchIDinofficial + "_score\">");
        sb.append("-");
        sb.append("</span>");
    }
    sb.append("</td>");
    //corner
    if (oddsType == "CHL") {
        sb.append("<td class=\"ccorner redColor\">");
        var normalTimeMatchStages = ["FirstHalf", "HalfTime", "SecondHalf"];
        var isShow = false;
        for (var i = 0; i < normalTimeMatchStages.length; ++i) {
            if (m.liveEvent!=null && m.liveEvent.matchstate == normalTimeMatchStages[i]) {
                isShow = true;
                break;
            }
        }
        if (m.chlodds.POOLSTATUS == 'Closed'
            || m.chlodds.POOLSTATUS == 'ResultIn'
            || m.chlodds.POOLSTATUS == 'Payout') {
            sb.append("<span id=\"" + m.matchIDinofficial + "_corner\">");
            sb.append("-");
            sb.append("</span>");
        }
        else if (m.chlodds.POOLSTATUS == 'NotSelling'
            || m.chlodds.POOLSTATUS == 'FinalStopSell'
            || m.cornerresult == "-1") {
            sb.append("<span id=\"" + m.matchIDinofficial + "_corner\">");
            sb.append("---");
            sb.append("</span>");
        }
        else if (m.IsMatchKickOff() && !isNonInplayAndNoLiveInfoMatch(m) && 
            isShow && 
            parseInt(m.cornerresult) >= 0 ) {
            sb.append("<span id=\"" + m.matchIDinofficial + "_corner\">");
            sb.append(m.cornerresult);
            sb.append("</span>");
        }
        else {
            sb.append("<span id=\"" + m.matchIDinofficial + "_corner\">");
            sb.append("-");
            sb.append("</span>");
        }
        sb.append("</td>");
    }
    //tv
    sb.append("<td class=\"ctv\"><span class=\"tv\" id=\"" + m.matchIDinofficial + "_tv" + "\">");
    sb.append(getTvStr(m));
    sb.append("</span></td>");
    //live cast
    sb.append("<td class=\"clive-cast\"><span id=\"" + m.matchIDinofficial + "_liveCast\">");
    sb.append(getLiveCastStr(m));
    sb.append("</span></td>");
    //goal
    if (oddsType == "FTS/NTS") {
        sb.append("<td class=\"cgoal\"><span id=\"ntspartdisplay_" + m.matchIDinofficial + "\"");
        if (pool.name == "FTS") {
            sb.append(" onmouseover=\"javascript:openTips(this,'fts');\" onmouseout=\"javascript:closeTips();\">");
            sb.append("F");
        } else if (pool.name == "NTS" || pool.name == "ETS") {
            sb.append(" onmouseover=\"javascript:openTips(this,'nts')\" onmouseout=\"javascript:closeTips()\">");
            sb.append(pool[0].ITEM);
        }
        sb.append("</span>");
        if (pool.name == "NTS" || pool.name == "ETS") {
            sb.append("<span style=\"display:none\" id=\"ntspart_" + m.matchIDinofficial + "\">").append(pool[0].ITEM).append("</span>");
        }
        sb.append("</td>");
    }

    //odds
    sb.append(drawOddsHtml(coupon, m, oddsType, pool));
    sb.append("</tr>");

    return sb.toString();
}

function cntGoalNumber(_intGoal) {
    var intGoal = parseInt(_intGoal);
    var cntGoal = "";
    if (jsLang == "EN") {
        cntGoal = "th";

        if (intGoal < 11 || intGoal > 20) {
            if (intGoal % 10 == 1) {
                cntGoal = "st";
            } else if (intGoal % 10 == 2) {
                cntGoal = "nd";
            } else if (intGoal % 10 == 3) {
                cntGoal = "rd";
            }
        }
    }
    return intGoal + cntGoal;
}

function teamMouseOver(mid) {
    $("#" + mid + "_hteam").addClass("mOver");
    $("#" + mid + "_hteam").css("cursor", "pointer");
    $("#" + mid + "_vs").addClass("mOver");
    $("#" + mid + "_ateam").addClass("mOver");
    $("#" + mid + "_ateam").css("cursor", "pointer");
}

function teamMouseOut(mid) {
    $("#" + mid + "_hteam").removeClass("mOver");
    $("#" + mid + "_hteam").css("cursor", "auto");
    $("#" + mid + "_vs").removeClass("mOver");
    $("#" + mid + "_ateam").removeClass("mOver");
    $("#" + mid + "_ateam").css("cursor", "auto");
}

function genHomeTeamTable(m, aTag) {
    var sb = new StringBuffer();
    sb.append("<td id=\"" + m.matchIDinofficial + "_hteam\" class=\"teamname\"");
    if (aTag != "") {
        sb.append(" onmouseover=\"teamMouseOver('" + m.matchIDinofficial + "')\"");
        sb.append(" onmouseout=\"teamMouseOut('" + m.matchIDinofficial + "')\"");
        sb.append(" onclick=\"" + aTag + "\"");
    }
    sb.append("><span>" + m.homeTeam["teamName" + jsLang] + "</span></td>");
    return sb.toString();
}

function genHomeRedCard(m, aTag) { // CMC - to be changed
    var sb = new StringBuffer();
    var noOfRedCard = getNoOfRedCard(m, "home");
    if (noOfRedCard > 0) {
        sb.append("<td style=\"width:10px;border-left:none;text-align:right\" id=\"" + m.matchIDinofficial + "_hred\" class=\"home_red_card\">");
        sb.append("<span><img src=\"" + footImagePath + "redcard_" + noOfRedCard + ".gif?CV=" + cv + "\"");
        sb.append(" title=\"" + GetGlobalResources("RedCard", "js") + ":" + noOfRedCard + "\" onerror=\"errImg(this);\" />");
    }
    else {
        sb.append("<td style=\"width:0px;border-left:none\" id=\"" + m.matchIDinofficial + "_hred\">");
        sb.append("<span><img src=\"" + footImagePath + "spacer.gif\" width=\"0\" height=\"0\" />");
    }
    sb.append("</span></td>");
    return sb.toString();
}

function genVs(m, aTag) {
    var sb = new StringBuffer();
    sb.append("<td style=\"width:14px;border-left:none;text-align:center\" id=\"" + m.matchIDinofficial + "_vs\" class=\"span_vs\"><span>");
    sb.append(GetGlobalResources("VS", "js"));
    sb.append("</span></td>");
    return sb.toString();
}

function genAwayRedCard(m, aTag) { // CMC - to be changed
    var sb = new StringBuffer();
    var noOfRedCard = getNoOfRedCard(m, "away");
    if (noOfRedCard > 0) {
        sb.append("<td style=\"width:10px;border-left:none;text-align:left\" id=\"" + m.matchIDinofficial + "_ared\" class=\"away_red_card\">");
        sb.append("<span><img src=\"" + footImagePath + "redcard_" + noOfRedCard + ".gif?CV=" + cv + "\"");
        sb.append(" title=\"" + GetGlobalResources("RedCard", "js") + ":" + noOfRedCard + "\" onerror=\"errImg(this);\" />");
    }
    else {
        sb.append("<td style=\"width:0px;border-left:none\" id=\"" + m.matchIDinofficial + "_ared\">");
        sb.append("<span><img src=\"" + footImagePath + "spacer.gif\" width=\"0\" height=\"0\" />");
    }
    sb.append("</span></td>");
    return sb.toString();
}

function genAwayTeamTable(m, aTag) {
    var sb = new StringBuffer();
    sb.append("<td style=\"border-left:none\" id=\"" + m.matchIDinofficial + "_ateam\" class=\"teamname\"");
    if (aTag != "") {
        sb.append(" onmouseover=\"teamMouseOver('" + m.matchIDinofficial + "')\"");
        sb.append(" onmouseout=\"teamMouseOut('" + m.matchIDinofficial + "')\"");
        sb.append(" onclick=\"" + aTag + "\"");
    }
    sb.append("><span>" + m.awayTeam["teamName" + jsLang] + "</span></td>");
    return sb.toString();
}

function getNeutralGround(m, aTag) {
    var sb = new StringBuffer();
    if ((m.neutralgroundvenue !== undefined && m.neutralgroundvenue !== null)) {
        var ngText = (m.neutralgroundvenue["neutralgroundvenueName" + jsLang] == "") ? ng : (ng1 + " " + m.neutralgroundvenue["neutralgroundvenueName" + jsLang] + " " + ng2);
        sb.append("<td style=\"width:16px;border-left:none\" id=\"" + m.matchIDinofficial + "_ng\" class=\"neutral_ground\">");
        sb.append("<span><img class=\"neutral_ground\" src=\"" + footImagePath + "icon_neutral.gif?CV=" + cv + "\" title=\"" + ngText + "\" onerror=\"errImg(this);\" />");
    }
    else {
        sb.append("<td style=\"width:0px;border-left:none\" id=\"" + m.matchIDinofficial + "_ng\">");
        sb.append("<span><img src=\"" + footImagePath + "spacer.gif\" width=\"0\" height=\"0\" />");
    }
    sb.append("</span></td>");
    return sb.toString();
}

function getTeamStr(m) {
    var sb = new StringBuffer();
    var aTag = "";
    if (!isMatchFinish(m))
        aTag = "callMatchInfo('?tdate=" + m.tdate + "&tday=" + m.matchDay + "&tnum=" + m.matchNum + "')";
    sb.append(genHomeTeamTable(m, aTag));
    sb.append(genHomeRedCard(m, aTag));
    sb.append(genVs(m, aTag));
    sb.append(genAwayRedCard(m, aTag));
    sb.append(genAwayTeamTable(m, aTag));
    sb.append(getNeutralGround(m, aTag));
    return sb.toString();
}

function getTvStr(match) {
    var sb = new StringBuffer();
    if (match != null) {
        try {
            var betSlip = top.document.getElementById('betSlipFrame');
            if (checkIsLogin() && hasWebTV(match.matchID) && betSlip && betSlip.contentWindow.GetDataStore('football_live_ind') == "Y") {
                if (match.IsMatchKickOff())
                    sb.append("<a href=\"javascript:top.betSlipFrame.openWebTVWindow('" + match.matchID + "');\">");
                else
                    sb.append("<a href=\"javascript:top.betSlipFrame.openWebTVWindow();\">");
                sb.append("<img src=\"" + footImagePath + "tv.gif?CV=" + cv + "\"");
                sb.append("alt=\"\" title=\"" + jsfootballLiveSchedule + "\" onerror='errImg(this);' \>");
                sb.append("</a>");
            } else {
                if (match.channel != undefined && match.channel != null && match.channel.length > 0) {
                    sb.append("<a href=\"javascript:goTVUrl();\">");
                    sb.append("<img src=\"" + nasImagePath + "icon_tv-" + match.channel[0].channelID + ".gif?CV=" + cv + "\"");
                    var txt = "";
                    for (var k = 0; k < match.channel.length; k++) {
                        txt = txt + match.channel[k].channelID + "-" + match.channel[k]["channelName" + jsLang] + " \n";
                    }
                    sb.append("alt=\"" + txt + "\" title=\"" + txt + "\" onerror='errImg(this);' \>");
                    sb.append("</a>");
                }
            }
        }
        catch (ex) {
        }
    }
    return sb.toString();
}

function getLiveCastStr(match) {
    var sb = new StringBuffer();
    if (match != null) {
        var betRadarId = getBetRadarId(match.matchID);
        if (betRadarId != '') {
            var liveCastPara = "id=249&layoutid=1&matchid=" + betRadarId + "&language=" + (jsLang == "EN" ? "en" : "zht");
            sb.append("<a href=\"javascript:callLiveCast('?" + liveCastPara + "')\">");
            sb.append("<img src=\"" + footImagePath + "t.gif?CV=" + cv + "\" title=\"\" onerror=\"errImg(this);\"/></a>");
        }
    }
    return sb.toString();
}

//get html of odds,oddsType:HAD,HIL,CHL,FTS,NTS
function drawOddsHtml(coupon, m, oddsType, pool) {
    var sb = new StringBuffer();
    if (pool != null) {
        var isSelling = checkIsSell(pool);
        var isPoolRemoved = false; // pool.isRemoved || pool.isPurged;
        var canFormAllUp = isSelling // pool is start sell
                        && m.inplaydelay == "false" // pool is not in-play-ing
                        && pool.ALLUP == "true";
        if (pool.name == "HAD") {
            sb.append(drawOddsItemHtml(coupon, pool, "H", 1, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved));
            sb.append(drawOddsItemHtml(coupon, pool, "D", 1, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved));
            sb.append(drawOddsItemHtml(coupon, pool, "A", 1, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved));
        } else if (pool.name == "HIL" || pool.name == "CHL") {
            //pool.LINELIST = pool.LINELIST.sort(sortMultipleLines);
            if (pool.LINELIST.length > 1) {
                // sort oddsset with mainline goes first (if isMainLineOnTop), then ascending order of goalline
                pool.LINELIST = pool.LINELIST.sort(function (a, b) {
                    var aLine = a.LINE.split('/');
                    var bLine = b.LINE.split('/');;
                    return ((parseFloat(aLine[0]) - parseFloat(bLine[0])) || (parseFloat(aLine.length == 1 ? 0 : aLine[1]) - parseFloat(bLine.length == 1 ? 0 : bLine[1])));
                }).sort(function (a, b) {
                    if (isMainLineOnTop) {
                        if (a.MAINLINE == "true" && b.MAINLINE == "false")
                            return -1;
                        if (a.MAINLINE == "false" && b.MAINLINE == "true")
                            return 1;
                    }
                    return 0;
                });
            }
            var showExpandButton = (pool.LINELIST.length > 1) ? 1 : 0;
            sb.append("<td class=\"cline\">");
            if (hasMLOddsChange(m.matchIDinofficial, pool))
                multipleLinePoolIds["m" + m.matchIDinofficial] = 1;

            checkMainlineChange(m.matchIDinofficial, pool);

            for (var i = 0; i < 5; i++) {
                var line = '';
                var mainline = false;
                if (pool.LINELIST[i] != null) {
                    line = pool.LINELIST[i].LINE || "";
                    mainline = pool.LINELIST[i].MAINLINE == "true";
                }
                sb.append("<div class=\"mlMainRow\" id=\"" + m.matchIDinofficial + "_" + pool.name);
                sb.append("_LINE" + ((i > 0) ? '_' + i : "") + "\" style=\"");
                var displayStyle = 'display:none';
                if (mainline || (multipleLinePoolIds["m" + m.matchIDinofficial] == 1 && i < lineRowCount[coupon + '_' + m.matchIDinofficial]))
                   displayStyle = '';
                sb.append(displayStyle);
                sb.append("\">");
                sb.append("[").append(line).append("]</div>");
            }

            sb.append("</td>");
            sb.append(drawOddsItemHtml(coupon, pool, "H", pool.LINELIST.length, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved, -1));
            sb.append(drawOddsItemHtml(coupon, pool, "L", pool.LINELIST.length, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved, showExpandButton));
        } else if (pool.name == "NTS" || pool.name == "ETS") {
            sb.append(drawOddsItemHtml(coupon, pool, "H", 1, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved));
            sb.append(drawOddsItemHtml(coupon, pool, "N", 1, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved));
            sb.append(drawOddsItemHtml(coupon, pool, "A", 1, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved));
        } else if (pool.name == "FTS") {
            sb.append(drawOddsItemHtml(coupon, pool, "H", 1, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved));
            sb.append(drawOddsItemHtml(coupon, pool, "N", 1, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved));
            sb.append(drawOddsItemHtml(coupon, pool, "A", 1, m.matchIDinofficial, isSelling, canFormAllUp, isPoolRemoved));
        }
    }
    return sb.toString();
}

//draw odds td,betType:HAD,HIL,CHL,FTS,NTS
function drawOddsItemHtml(coupon, pool, itemName, rowCount, matchID, sell, canAllUp, isPoolRemoved, hasExpandButton) {
    var sb = new StringBuffer();
    var betType = pool.name;
    var oddsClass = "codds-had";
    if (betType == "NTS" || betType == "FTS") {
        oddsClass = "codds-nts";
    } else if (betType == "HIL") {
        oddsClass = "codds-hil";
    } else if (betType == "CHL") {
        oddsClass = "codds-chl";
    }

    sb.append("<td style=\"white-space:nowrap\" class=\"" + oddsClass + " codds\">");
    for (var i = 0; i < rowCount; i++) {
        var isSelling = sell;
        var odds = '';
        var mainline = false;
        var lineNo = 1;
        if (pool.name == "HAD" || pool.name == "FTS") {
            odds = pool[itemName];
        } else if (pool.name == "ETS" || pool.name == "NTS") {
            odds = pool[0][itemName];
        } else {
            odds = pool.LINELIST[i][itemName];
        }
        if (betType == "HIL" || betType == "CHL") {
            isSelling = isSelling && (pool.LINELIST[i].LINESTATUS == "1");
            mainline = (pool.LINELIST[i].MAINLINE == "true");
            lineNo = pool.LINELIST[i].LINENUM;
        }

        var chkName = "chk" + betType;
        var spanID = matchID + "_" + betType + "_" + itemName + ((i > 0) ? '_' + i : "");
        var chkID = matchID + "_" + betType + "_" + itemName + ((i > 0) ? '_' + i : "") + "_c";
        var oddsText = (odds && odds.split("@")[1]) ? odds.split("@")[1] : "---";
        var oddsStatus = (odds && odds.split("@")[0]) ? odds.split("@")[0] : "---";
        if (!isSelling || $.isNullOrEmpty(oddsText) || isPoolRemoved) {
            oddsText = "---";
        }
        var checkboxDisabled = !isSelling || oddsText == "RFD" || oddsText == "LSE" || oddsText == "---" || isDisabled(oddsStatus);
        if (checkboxDisabled && selectionCheckBox[chkID]) {
            selectionCheckBox[chkID] = false;
        }
        var boxcheck = isSelling && isSelectionCheckBoxChecked(chkID);
        sb.append("<div id=\"mlId" + matchID + itemName + "_" + i + "\" class=\"mlMainRow" + ((!mainline) ? " otherLineRow" : "") + (boxcheck ? " checkedOdds" : "") + "\" style=\"");
        var displayStyle = 'display:none';
        if ((betType != "HIL" && betType != "CHL") || mainline || (multipleLinePoolIds["m" + matchID] == 1 && i < lineRowCount[coupon + '_' + matchID]))
            displayStyle = '';
        sb.append(displayStyle);
        sb.append("\"><span>");
        sb.append("<input type=\"checkbox\" name=\"" + chkName + "\" id=\"" + chkID + "\" lineNo=\"" + lineNo + "\" value=\"\" onclick=\"tgTD(this);")
            .append("setSelectionCheckBox('" + chkID + "', this);\"");
        if (checkboxDisabled) {
            sb.append(" disabled=\"disabled\"");
        }
        if (boxcheck) {
            sb.append(" checked");
        }
        sb.append("/>");
        if (canAllUp && oddsText != "---") {
            sb.append("<a class=\"oddsLink\" href=\"javascript:calBet(this,'" + matchID + "','" + betType + "','" + itemName + "','"
			+ ((i > 0) ? i : "")
			+ "');\" title=\"" + GetGlobalResources("AllupCalculator", "js") + "\">");
        } else {
            sb.append("<a class=\"oddsLink noUL\">");
        }
        sb.append("<span id=\"" + spanID + "\" ");
        if (oldOdds[spanID] != null && oldOdds[spanID] != oddsText && oddsText != "---") {
            clearTimeout(timeoutObj[spanID]);
            sb.append('class="oupt"');
            timeoutObj[spanID] = setTimeout(function () { $('#' + spanID).removeClass('oupt'); }, 120000);
            timeoutDT[spanID] = new Date();
        }
        else if (boldText(timeoutDT[spanID])) {
            sb.append('class="oupt"');
        }
        sb.append(">");
        if (odds == "RFD") {
            sb.append(jsRFD);
        }
        else if (odds == "LSE") {
            sb.append(jsLSE);
        } else {
            sb.append(oddsText);
            oldOdds[spanID] = oddsText;
        }
        sb.append("</span></a></span>");
        sb.append("</div>");
    }
    sb.append("</td>");
    if (hasExpandButton > -1) {
        sb.append("<td class='tgIndMl mlinebtn'>");
        sb.append("<span id=\"mlExpandBtn_" + matchID + "\" style=\"cursor:pointer;");
        if (hasExpandButton <= 0)
            sb.append("display:none;");
        sb.append("\" class=\"");
        sb.append((multipleLinePoolIds["m" + matchID] == 1) ? "spBtnMinus" : "spBtnPlus");
        sb.append("\" onclick=\"toggleMLDisplay(" + coupon + ", '" + matchID + "','" + pool.name + "')\"></span>");
        sb.append("</td>");
    }
    return sb.toString();
}

function boldText(lastDT) {
    var curDT = new Date();
    return lastDT != null && (((curDT.getTime() - lastDT.getTime()) / 1000) < 120);
}

function tgILC(coupon) {
    if (showHideBtn[coupon] == 1)
        collapseILC(coupon);
    else
        expandILC(coupon);
}

function expandILC(coupon) {
    showHideBtn[coupon] = 1;
    $('#tgCouBtn' + coupon).addClass("spBtnMinus");
    $('#tgCouBtn' + coupon).removeClass("spBtnPlus");
    for (var key in lineRowCount) {
        var tmp = key.split('_');
        if (coupon == tmp[0])
            $("#rmid" + tmp[1]).show();
    }
}

function collapseILC(coupon) {
    showHideBtn[coupon] = 0;
    $('#tgCouBtn' + coupon).addClass("spBtnPlus");
    $('#tgCouBtn' + coupon).removeClass("spBtnMinus");
    for (var key in lineRowCount) {
        var tmp = key.split('_');
        if (coupon == tmp[0])
            $("#rmid" + tmp[1]).hide();
    }
}

function isAllMultipleLineButtonsExpand(coupon) {
    for (var key in lineRowCount) {
        if (lineRowCount[key] <= 1)
            continue;
        var tmp = key.split('_');
        if (coupon == tmp[0]) {
            if (multipleLinePoolIds["m" + tmp[1]] != 1)
                return false;
        }
    }
    return true;
}

function isAllMultipleLineButtonsCollapse(coupon) {
    for (var key in lineRowCount) {
        if (lineRowCount[key] <= 1)
            continue;
        var tmp = key.split('_');
        if (coupon == tmp[0]) {
            if (multipleLinePoolIds["m" + tmp[1]] == 1)
                return false;
        }
    }
    return true;
}

function expandLines(coupon, matchId, oddsType) {
    multipleLinePoolIds["m" + matchId] = 1;
    $("#mlExpandBtn_" + matchId).removeClass("spBtnPlus").addClass("spBtnMinus");
    for (var i = 0; i < lineRowCount[coupon + '_' + matchId]; i++) {
        $("#" + matchId + "_" + oddsType + "_LINE" + (i > 0 ? "_" + i : "")).show();
        $("#mlId" + matchId + "H" + "_" + i).show();
        $("#mlId" + matchId + "L" + "_" + i).show();
    }
}

function collapseLines(coupon, matchId, oddsType) {
    multipleLinePoolIds["m" + matchId] = 0;
    $("#mlExpandBtn_" + matchId).removeClass("spBtnMinus").addClass("spBtnPlus");
    var match = getMatch(matchId);
    var pool = getPool(match, oddsType);
    for (var i = 0; i < pool.LINELIST.length; i++) {
        if (pool.LINELIST[i] != undefined && pool.LINELIST[i] != null && pool.LINELIST[i].MAINLINE != "true") {
            $("#" + matchId + "_" + oddsType + "_LINE" + (i > 0 ? "_" + i : "")).hide();
            $("#mlId" + matchId + "H" + "_" + i).hide();
            $("#mlId" + matchId + "L" + "_" + i).hide();
        }
    }
}

function toggleMLDisplay(coupon, matchId, oddsType) {
    if (multipleLinePoolIds["m" + matchId] != 1) { // to expand
        expandLines(coupon, matchId, oddsType);
        if (isAllMultipleLineButtonsExpand(coupon)) {
            $("#tgAllMLBtn_" + coupon).html(GetGlobalResources("CollapseAll", "js") + "<span class=\"spBtnMinus\"></span>");
            multipleLinePoolIds[coupon + "_ALL"] = 1;
        }
    }
    else { // to collapse
        collapseLines(coupon, matchId, oddsType);
        //if ( isAllMultipleLineButtonsCollapse(coupon) ) {
        $("#tgAllMLBtn_" + coupon).html(GetGlobalResources("ExpandAll", "js") + "<span class=\"spBtnPlus\"></span>");
        multipleLinePoolIds[coupon + "_ALL"] = 0;
        //}
    }

}

function toggleAllMLDisplay(e, coupon, oddsType) {
    var event = e || window.liveevent;
    if (event.stopPropagation) {
        event.stopPropagation();
    }
    else {
        e.cancelBubble = true;
    }

    if (showHideBtn[coupon] != 1)
        expandILC(coupon);
    if (multipleLinePoolIds[coupon + "_ALL"] != 1) { //expand all
        for (var key in lineRowCount) {
            var tmp = key.split('_');
            if (coupon == tmp[0])
                expandLines(coupon, tmp[1], oddsType);
        }
        $("#tgAllMLBtn_" + coupon).html(GetGlobalResources("CollapseAll", "js") + "<span class=\"spBtnMinus\"></span>");
        multipleLinePoolIds[coupon + "_ALL"] = 1;
    }
    else if (multipleLinePoolIds[coupon + "_ALL"] == 1) {
        for (var key in lineRowCount) {
            var tmp = key.split('_');
            if (coupon == tmp[0])
                collapseLines(coupon, tmp[1], oddsType);
        }
        $("#tgAllMLBtn_" + coupon).html(GetGlobalResources("ExpandAll", "js") + "<span class=\"spBtnPlus\"></span>");
        multipleLinePoolIds[coupon + "_ALL"] = 0;
    }
}

//display the selected matches
function showSelectedMatches() {
    $("#divLoading").show();
    selectionCheckBox = [];
    isShowSelected = true;
    curPage = 1;
    render();
    closeEventWindow();
}

//display all matches,oddsType:HAD,HIL,CHL,FTS/NTS
function showAllMatches(oddsType) {
    //delete the event window
    selectionCheckBox = [];
    isShowSelected = false;
    oddsType = oddsType.toUpperCase();
    closeEventWindow();
    $(".selLeague select").eq(0).val("all");
    leagueCode = "ALL";
    hasChannel = "ALL";
    isLiveCast = "ALL";
    hasInplayPool = "ALL";
    curPage = 1;
    render();
}

//
function showInplay(oddsType) {
    $("#divLoading").show();
    selectionCheckBox = [];
    hasChannel = "ALL";
    isLiveCast = "ALL";
    hasInplayPool = "true";
    curPage = 1;
    render();
    closeEventWindow();
}

//get the paged matches from filtered matches
function getPagedMatches(matchesArr, pageNo, pageSize) {
    if (matchesArr == null) return;
    var arr = new Array();
    var counter = 0;
    var startIndex = (pageNo - 1) * pageSize;
    var endIndex = pageNo * pageSize - 1;
    for (var i = 0; i < matchesArr.length; i++) {
        if (matchesArr[i].matches == undefined || matchesArr[i].matches == null) {
            matchesArr[i].matches = [];
        }
        var matches = matchesArr[i].matches;
        var obj = {};
        obj.name = matchesArr[i].name;
        obj.matches = new Array();
        var sIndex = startIndex - counter;
        sIndex = sIndex < 0 ? 0 : sIndex;
        var eIndex = endIndex - counter;
        counter = counter + matches.length;
        if (matches.length == 0) {
            arr.push(obj);
        } else if ((sIndex + 1) <= matches.length && (eIndex + 1) <= matches.length) {//the startIndex and endIndex are in the same dimension
            obj.matches = matches.slice(sIndex, eIndex + 1);
            arr.push(obj);
            break;
        } else if ((sIndex + 1) <= matches.length && (eIndex + 1) > matches.length) {//the startIndex and endIndex are not in the same dimension
            obj.matches = matches.slice(sIndex);
            arr.push(obj);
            continue;
        } else if ((sIndex + 1) <= (counter - matches.length) && (endIndex + 1) <= matches.length) {//the startIndex and endIndex are not in the same dimension
            obj.matches = matches.slice(endIndex + 1);
            arr.push(obj);
            break;
        }
    }
    return arr;
}

//display the paged matches
function pager(pageNo, pageSize) {
    selectionCheckBox = [];
    oldOdds = [];
    $("#divLoading").show();

    curPage = pageNo;
    //delete the event window
    closeEventWindow();
    //display the matches
    showHideBtn = [1, 1];
    var $obj = $("#tbMatches");

    var displayedMatches = getPagedMatches(filteredMatches, curPage, pageSize);
    resetMultipleLine();
    setLineCount(displayedMatches, poolType);
    $obj.html(drawMatchesHtml(displayedMatches, poolType));
    //add betline
    resetBetLineArray();
    createBetLinesForDisplayMatches(displayedMatches, poolType);
    //display the pagers
    $("#divPager").html(drawPagerHtml(pageSize, filteredMatches.matchesCount, curPage, buttonCount));

    $("#divLoading").hide();
}

//get the pager
function drawPagerHtml(pageSize, totalRows, pageNo, buttonCount) {
    var sb = new StringBuffer();
    var sbPager = new StringBuffer();
    sb.append("<div class='pager'>");
    if (totalRows > pageSize) {
        sbPager.append("<div class='pageNum'>");
        sbPager.append("&lt;&lt;");
        if (pageNo > 1) {
            sbPager.append("<a href=\"javascript:pager(" + (pageNo - 1) + "," + pageSize + ")\">");
            sbPager.append(GetGlobalResources("Previous", "js"));
            sbPager.append("</a>");
        }
        var pages = totalRows % pageSize == 0 ? Math.floor(totalRows / pageSize) : Math.floor(totalRows / pageSize) + 1;
        var startIndex = 1;
        var toIndex = buttonCount;
        var tmpNum = (Math.floor(pageNo / buttonCount)) * buttonCount;
        if (pages > buttonCount) {
            if (pageNo > buttonCount) {
                if (pageNo > tmpNum) {
                    sbPager.append("<span>|</span>");
                    sbPager.append("<a href=\"javascript:pager(" + tmpNum + "," + pageSize + ")\">");
                    sbPager.append("...");
                    sbPager.append("</a>");
                    startIndex = tmpNum + 1;
                    toIndex = (pages - tmpNum) < buttonCount ? pages : tmpNum + buttonCount;
                } else if (pageNo == tmpNum) {
                    sbPager.append("<span>|</span>");
                    sbPager.append("<a href=\"javascript:pager(" + (pageNo - buttonCount) + "," + pageSize + ")\">");
                    sbPager.append("...");
                    sbPager.append("</a>");
                    startIndex = pageNo - buttonCount + 1;
                    toIndex = pageNo;
                }
            }
        } else {
            toIndex = pages;
        }
        for (var i = startIndex; i <= toIndex; i++) {
            if (pageNo != i) {
                sbPager.append("<a href=\"javascript:pager(" + i + "," + pageSize + ")\">");
                sbPager.append(i);
                sbPager.append("</a>");
            } else {
                sbPager.append("<b>" + i + "</b>");
            }
            sbPager.append("<span>|</span>");
        }
        if (pages > buttonCount) {
            if (pageNo > tmpNum && pageNo <= tmpNum + buttonCount && (tmpNum + buttonCount) < pages) {
                sbPager.append("<a href=\"javascript:pager(" + (tmpNum + buttonCount + 1) + "," + pageSize + ")\">");
                sbPager.append("...");
                sbPager.append("</a>");
            } else if (pageNo == tmpNum) {
                sbPager.append("<a href=\"javascript:pager(" + (pageNo + 1) + "," + pageSize + ")\">");
                sbPager.append("...");
                sbPager.append("</a>");
            }
        }
        if (pageNo < pages) {
            sbPager.append("<a href=\"javascript:pager(" + (pageNo + 1) + "," + pageSize + ")\">");
            sbPager.append(GetGlobalResources("Next", "js"));
            sbPager.append("</a>");
        }
        sbPager.append("&gt;&gt;");
        sbPager.append("</div>");
    }
    var sbPagerInfo = new StringBuffer();
    sbPagerInfo.append("<div class='pageInfo'>");
    sbPagerInfo.append(GetGlobalResources("Pagination1", "js"));
    if (totalRows > 0) {
        sbPagerInfo.append(" ");
        sbPagerInfo.append((pageNo - 1) * pageSize + 1);
        sbPagerInfo.append(" - ");
        sbPagerInfo.append(pageNo * pageSize > totalRows ? totalRows : pageNo * pageSize);
        sbPagerInfo.append(" ");
    } else {
        sbPagerInfo.append("0");
    }
    sbPagerInfo.append(GetGlobalResources("Pagination2", "js"));
    sbPagerInfo.append(totalRows);
    sbPagerInfo.append(GetGlobalResources("Pagination3", "js"));
    sbPagerInfo.append("</div>");
    sb.append(sbPagerInfo.toString());
    sb.append(sbPager.toString());
    sb.append("</div>");

    return sb.toString();
}

//display the dropdownlist
function openDropdown(dropdownObj, contentID, event) {
    var pos = $(dropdownObj).offset();
    var top = pos.top + $(dropdownObj).height();
    $("#" + contentID).css({ position: "absolute", top: top, left: pos.left, zIndex: "1000", backgroundColor: "#DFE9FF", width: "120px", overflow: "hidden" });
    $(".popup").each(function () {
        if ($(this).attr("id") == contentID) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
    var e = event ? event : window.liveevent;
    if (window.liveevent) {
        e.cancelBubble = true;
    } else {
        e.stopPropagation();
    }
    var clearPopup = function () {
        setTimeout(function () {
            $(".popup").each(function () {
                $(this).hide();
            });
        }, 500);
        $(document).unbind("click");
        $("*").unbind("touchstart", clearPopup);

    }
    $(document).bind("click", function () {
        $(".popup").each(function () {
            $(this).hide();
        });
        $(document).unbind("click");
        $("*").unbind("touchstart", clearPopup);
    });
    $("*").bind("touchstart", clearPopup);
}

//filter matches by channel / livecast
function filter(val, flag) {
    $("#divLoading").show();
    selectionCheckBox = [];
    if (flag == "channel") {
        hasChannel = val;
        $("#channel-content").hide();
    } else if (flag == "livecast") {
        isLiveCast = val;
        $("#liveCast-content").hide();
    }
    curPage = 1;
    render();
    closeEventWindow();
}

//display the event window,oddsType:HAD,HIL,CHL,FTS,NTS
function openEventWindow(obj, matchID, oddsType) {
    if ($("#divDetails").length > 0) {
        closeEventWindow();
    }
    var match = getMatch(matchID);
    if (match != null && match.IsMatchKickOff() && !isNonInplayAndNoLiveInfoMatch(match)) {
        $("#ilcMatches").append("<div id=\"divDetails\"></div>");
        $("#divDetails").html(drawEventHtml(match, oddsType));
        var pos = $(obj).offset();
        var top = pos.top + $(obj).height();
        $("#divDetails").css({ position: "absolute", top: top, left: (pos.left - 200), width: "456px", zIndex: "1000", backgroundColor: "#fff" });
    }
}

function getMatch(matchID) {
    if (matchID == null) return;
    if (ilcMatches.length > 0) {
        return betValue[matchID];
    }
    return null;
}

//draw event html,oddsType:HAD,HIL,CHL,FTS,NTS
function drawEventHtml(match, oddsType) {
    if (match == null) return;

    var sb = new StringBuffer();
    sb.append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
    sb.append("<tr><td colspan=\"5\" class=\"crefresh\">");
    sb.append("<input type=\"hidden\" id=\"" + match.matchIDinofficial + "\" value=\"" + match.matchIDinofficial + "\" />");
    sb.append("<div>");
    sb.append("<span><a href=\"javascript:closeEventWindow();\"><img src=\"" + footImagePath + "green_closebutton.gif?CV=" + cv + "\" /></a></span>");
    if (oddsRefreshType != "push") {
        sb.append("<span class=\"refresh\"><a href=\"javascript:refreshMatches($('#selOddsType').val());\">");
        sb.append('<img src="' + commonImagePath + 'icon_refresh.gif?CV=' + cv + '" class="pointer icon" alt="' + GetGlobalResources("Refresh") + '" title="' + GetGlobalResources("Refresh") + '" onerror=\"errImg(this);\" />');
        sb.append("</a></span>");
    }
    var dt = new Date(serverTime);
    sb.append('<span>' + GetGlobalResources("RefreshAt") + ':' + toDateStringWithoutSec(dt) + '</span>');
    sb.append("</div></td></tr>");
    sb.append("<tr class=\"rhead\"><td colspan=\"2\" class=\"cteam\">");
    sb.append(match.homeTeam["teamName" + jsLang]);
    sb.append("</td><td class=\"cmin\">Min</td><td colspan=\"2\" class=\"cteam\">");
    sb.append(match.awayTeam["teamName" + jsLang]);
    sb.append("</td></tr>");
    if (match.liveEvent != null && match.liveEvent.liveevent != null && match.liveEvent.liveevent.length > 0) {
        //event:[['9','redCard','beckham','Home'],['15','goal','figo','Away'],['25','goal','figo','Away']]
        var eventArr = match.liveEvent.liveevent;
        for (var k = 0; k < eventArr.length; k++) {
            if (k == eventArr.length - 1) {
                sb.append("<tr class=\"rlast\">");
            } else {
                sb.append("<tr class=\"rcont\">");
            }
            var tmpArr = eventArr[k];
            if ((tmpArr.homeaway.toLowerCase() == "away" && tmpArr.actionType.toLowerCase() != "owngoal")
             || (tmpArr.homeaway.toLowerCase() == "home" && tmpArr.actionType.toLowerCase() == "owngoal")) {
                sb.append("<td class=\"cevent no-leftBorder\">&nbsp;</td><td class=\"cplayer\">&nbsp;</td>");
                sb.append("<td class=\"cmin\">");
                sb.append((tmpArr.minutesElasped != "-1") ? tmpArr.minutesElasped : "");
                sb.append("</td>");
                sb.append("<td class=\"cplayer\">");
                sb.append(tmpArr["playerName" + jsLang] != "" ? tmpArr["playerName" + jsLang] : tmpArr["playerNameEN"]);
                if (tmpArr.actionType.toLowerCase() == "owngoal")
                    sb.append(" (").append(GetGlobalResources("owngoal", "js")).append(")");
                sb.append("</td>");
            }
            if ((tmpArr.homeaway.toLowerCase() == "away" && tmpArr.actionType.toLowerCase() != "owngoal")
             || (tmpArr.homeaway.toLowerCase() == "home" && tmpArr.actionType.toLowerCase() == "owngoal")) {
                sb.append("<td class=\"cevent\">");
            } else {
                sb.append("<td class=\"cevent no-leftBorder\">");
            }
            if (tmpArr.actionType.toLowerCase() == "redcard" || tmpArr.actionType.toLowerCase() == "yellowredcard") {
                sb.append("<img src='" + footImagePath + "red_card.gif?CV=" + cv + "' title='' onerror='errImg(this);'/>");
            } else if (tmpArr.actionType.toLowerCase() == "yellowcard") {
                sb.append("<img src='" + footImagePath + "yellow_card.gif?CV=" + cv + "' title='' onerror='errImg(this);'/>");
            } else {
                sb.append("<img src='" + footImagePath + "icon_ball.gif?CV=" + cv + "' title='' onerror='errImg(this);'/>");
            }
            sb.append("</td>");
            if ((tmpArr.homeaway.toLowerCase() == "home" && tmpArr.actionType.toLowerCase() != "owngoal")
             || (tmpArr.homeaway.toLowerCase() == "away" && tmpArr.actionType.toLowerCase() == "owngoal")) {
                sb.append("<td class=\"cplayer\">");
                sb.append(tmpArr["playerName" + jsLang] != "" ? tmpArr["playerName" + jsLang] : tmpArr["playerNameEN"]);
                if (tmpArr.actionType.toLowerCase() == "owngoal")
                    sb.append(" (").append(GetGlobalResources("owngoal", "js")).append(")");
                sb.append("</td>");
                sb.append("<td class=\"cmin\">");
                sb.append((tmpArr.minutesElasped != "-1") ? tmpArr.minutesElasped : "");
                sb.append("</td>");
                sb.append("<td class=\"cplayer\">&nbsp;</td><td class=\"cevent\">&nbsp;</td>");
            }
            sb.append("</tr>");
        }
    }
    sb.append("</table>");

    return sb.toString();
}

//get all new matches to refresh the page,oddsType:HAD,HIL,CHL,FTS/NTS
var enableRefresh = true;
function refreshMatches(oddsType) {
    if (!enableRefresh)
        return;

    enableRefresh = false;
    $("#divLoading").show();
    $.ajax({
        type: "GET",
        //url: "../getIlcMatchesString.ashx?lang=" + jsLang,
        url: "../getJSON.aspx?jsontype=odds_ilc.aspx",
        success: function (data) {
            //eval(data);
            //data = JSON.parse(data);
            ilcMatches = [];
            for (var i = 0; i < 2; i++) {
                if (getMatchLength(data[i]) == 0)
                    data[i].matches = [];
            }
            ilcMatches.push(data[0]);
            ilcMatches.push(data[1]);
            reRender();
            $("#divLoading").hide();
        },
        error: function () {
            $("#divLoading").hide();
        }
    });

    setTimeout(function () { enableRefresh = true }, autoRefreshInterval * 1000);
}

function autoRefreshServerTime() {
    $.ajax({
        type: "GET",
        url: "../getJSON.aspx?jsontype=time",
        success: function (data) {
            setLastUpdateTime(data);
            reRender();
        },
        error: function () {
        }
    });
}

function updateSimpleMatchList() {
    $.ajax({
        type: "GET",
        url: "../getJSON.aspx?jsontype=fullmatchlist",
        success: function (data) {
            simpleMatchList = data;
            reRender();
        },
        error: function () {
        }
    });
    setTimeout(function () { updateSimpleMatchList(); }, autoRefreshInterval * 1000);
}

function getBetRadarId(matchId) {
    for (var i in simpleMatchList) {
        if (matchId == simpleMatchList[i].mID)
            return simpleMatchList[i].brID;
    }
    return "";
}

function hasLiveInfo(matchId) {
    for (var i in simpleMatchList) {
        if (matchId == simpleMatchList[i].mID)
            return simpleMatchList[i].hasLiveInfo;
    }
    return false;
}

function hasWebTV(matchId) {
    for (var i in simpleMatchList) {
        if (matchId == simpleMatchList[i].mID)
            return simpleMatchList[i].hasWebTV;
    }
    return false;
}

function isBetRadarIncomplete(matchId) {
    for (var i in simpleMatchList) {
        if (matchId == simpleMatchList[i].mID)
            return simpleMatchList[i].isIncomplete;
    }
    return false;
}

function checkIsRenderNeeded(match) {
    var isRenderNeeded = false;
    if (ilcMatches != null || match != null) {
        for (var i = 0; i < ilcMatches.length; i++) {
            for (var j = 0; j < getMatchLength(ilcMatches[i]) ; j++) {
                var m = ilcMatches[i].matches[j];
                if (m.matchIDinofficial == match.matchIDinofficial) {
                    if (m.isRemoved != match.isRemoved || m.toDisplayIlc != match.toDisplayIlc/* || m.isEmergency != match.isEmergency*/
                        || m.esst != match.esst || m.isMatchOfDay != match.isMatchOfDay) {
                        isRenderNeeded = true;
                        break;
                    }
                }
            }
            if (isRenderNeeded) {
                break;
            }
        }
    }
    return isRenderNeeded;
}

//check if the ilcMatches has mathces
function checkHasMatches() {
    var hasMatches = false;
    if (ilcMatches != null) {
        for (var i = 0; i < ilcMatches.length; i++) {
            if (getMatchLength(ilcMatches[i]) > 0) {
                hasMatches = true;
                break;
            }
        }
    }
    return hasMatches;
}

//close the event window
function closeEventWindow() {
    $("#divDetails").remove();
}

function checkValueNulltoEmpty(value) {
    if (value == undefined || value == null) {
        return "";
    } else {
        return value;
    }
}

function ConvertToBool(value) {
    var res = false;
    if (value == undefined || value == null || value == "") {
        return false;
    } else {
        if (value == true || value.toLowerCase() == "true") {
            res = true;
        }
    }
    return res;
}


function resetBetLineArray() {
    matchIDArr = new Array();
    betValue = new Array();
    poolSellValue = new Array();
}

//insert a new betline
function insertNewBetLine(match, oddsType) {
    if (match != null && oddsType != null && oddsType != "") {
        var pool = getPool(match, oddsType);
        if (pool != null) {
            matchIDArr[matchIDArr.length] = match.matchIDinofficial;
            //betValue[match.matchIDinofficial] = match;
            poolSellValue[poolSellValue.length] = checkIsSell(pool) ? "1" : "0";
        }
    }
}

//delete the betline
function deleteBetLines(matchIdList) {
    if (matchIdList != null && matchIdList.length > 0) {
        for (var i = 0; i < matchIdList.length; i++) {
            deleteBetLine(matchIdList[i]);
        }
    }
}

//delete betline // CMC
function deleteBetLine(matchID) {
    for (var i = 0; i < matchIDArr.length; i++) {
        //var rawBetAttr = betValue[i][0].split(",")[0].split("**");
        var mID = matchIDArr[i];
        if (parseInt(matchID) == parseInt(mID)) {
            //betValue.splice(i, 1);
            poolSellValue.splice(i, 1);
            matchIDArr.splice(i, 1);
            break;
        }
    }
}

//update the betline,oddsType:HAD,HIL,CHL,FTS,NTS // CMC
function updateBetLine(match, oddsType) {
    if (match == null) return;
    var pool = getPool(match, oddsType);
    if (pool != null) {
        if (matchIDArr != null && matchIDArr.length > 0) {
            for (var i = 0; i < matchIDArr.length; i++) {
                var matchID = matchIDArr[i];
                var poolType = rawBetAttr[1];

                if (matchID == match.matchIDinofficial) {
                    //betValue[i] = match;
                    poolSellValue[i] = checkIsSell(pool) ? "1" : "0";
                    break;
                }
            }
        }
    }
}

//get the display matches' betline string,oddsType:HAD,HIL,CHL,FTS/NTS
function createBetLinesForDisplayMatches(displayedMatches, oddsType) {
    if (displayedMatches != null && displayedMatches.length > 0) {
        for (var i = 0; i < displayedMatches.length; i++) {
            for (var j = 0; j < getMatchLength(displayedMatches[i]) ; j++) {
                var match = displayedMatches[i].matches[j];
                var pool = getPool(match, oddsType);
                if (pool != null) {
                    matchIDArr[matchIDArr.length] = match.matchIDinofficial;
                    //betValue[betValue.length] = createBetLine(match, oddsType);
                    betValue[match.matchIDinofficial] = new Match(match);
                    poolSellValue[poolSellValue.length] = checkIsSell(pool) ? "1" : "0";
                }
            }
        }
    }
}
function getParameter(paramName) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + paramName + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}


//set page info
function setPageInfo(isDisplay) {
    var arr = new Array();
    arr.push($("table.ilcOdds"));
    arr.push($("#ulSubBar"));
    arr.push($("#liShowSelected"));
    arr.push($("#liShowAll"));
    arr.push($("#liShowInplay"));
    for (var i = 0; i < arr.length; i++) {
        if (isDisplay) {
            arr[i].show();
        } else {
            arr[i].hide();
        }
    }
    if (isDisplay) {
        clearNoPoolMsg();
    } else {
        clearNoPoolMsg();
        clearPagerMsg();
        var sb = new StringBuffer();
        sb.append("<div class=\"nopool\"><div class=\"nopoolmsg\">");
        sb.append(GetGlobalResources("NoPoolMsg", "js"));
        sb.append("</div></div>");
        $("#ilcOdds").append(sb.toString());
    }
}

//clear the no pool msg
function clearNoPoolMsg() {
    $("div.nopool").eq(0).remove();
}

//clear the pager msg
function clearPagerMsg() {
    $("#divPager").empty();
}

//set leagues
function setLeagues(matchesArray, currentVal, isPush) {
    var leaguesArr = new Array();
    leaguesArr.push({ leagueCode: "ALL", leagueName: GetGlobalResources("SelectLeague", "js") });
    if (!containsLeague(leaguesArr, currentVal)) {
        var $opt = $(".selLeague select option:selected").eq(0);
        var obj = new Object();
        obj.leagueCode = $opt.val();
        obj.leagueName = $opt.text();
        leaguesArr.push(obj);
    }

    if (matchesArray != null) {
        for (var i = 0; i < matchesArray.length; i++) {
            for (var j = 0; j < getMatchLength(matchesArray[i]); j++) {
                var m = matchesArray[i].matches[j];
                if (checkIsVoidMatch(m.matchStatus))
                    continue;
                var shortName = m.league.leagueShortName;
                if (shortName == "CLB" || shortName == "CUP" || shortName == "INT")
                    shortName = "others";
                if (!containsLeague(leaguesArr, shortName)) {
                    var obj = new Object();
                    obj.leagueCode = m.league.leagueShortName;
                    obj.leagueName = m.league["leagueName" + jsLang];
                    leaguesArr.push(obj);
                }
            }
        }
    }
    var buf = new StringBuffer();
    buf.append('<select onchange="filterByLeague($(this).val());">');
    var hasAddOthers = false;
    for (var k = 0; k < leaguesArr.length; k++) {
        var league = leaguesArr[k];
        if (league.leagueCode == "CLB" || league.leagueCode == "CUP" || league.leagueCode == "INT") {
            if (!hasAddOthers) {
                if (currentVal == "others") {
                    buf.append("<option selected =\"selected\" value=\"others\">" + GetGlobalResources("Others", "js") + "</option>");
                } else {
                    buf.append("<option value=\"others\">" + GetGlobalResources("Others", "js") + "</option>");
                }
                hasAddOthers = true;
            }
        } else {
            if (currentVal == league.leagueCode) {
                buf.append("<option selected =\"selected\" value=\"" + league.leagueCode + "\">" + league.leagueName + "</option>");
            } else {
                buf.append("<option value=\"" + league.leagueCode + "\">" + league.leagueName + "</option>");
            }
        }
    }
    buf.append('</select>');
    $('#leagueDD').html(buf.toString());
}

function containsLeague(leaguesArr, leagueCode) {
    var exist = false;
    if (leaguesArr != null) {
        for (var i = 0; i < leaguesArr.length; i++) {
            var obj = leaguesArr[i];
            if (obj.leagueCode == leagueCode) {
                exist = true;
                break;
            }
        }
    }
    return exist;
}


//get matchNum
function getMatchNum(match, oddsType) {
    var sb = new StringBuffer();
    if (match != null && oddsType != null && oddsType != "") {
        var matchNumTxt = GetGlobalResources(match.matchDay) + " " + match.matchNum;
        if (!isMatchFinish(match) && ((match.IsMatchKickOff() && match.inplayPools != null && match.inplayPools.length > 0) || !match.IsMatchKickOff())) {
            if (!match.IsMatchKickOff()) {
                sb.append("<a href=\"/football/odds/odds_allodds.aspx?");
            } else {
                sb.append("<a href=\"/football/odds/odds_inplay_all.aspx?");
            }
            sb.append("lang=" + jsLang + "&tmatchid=" + match.matchID + "\"");
            sb.append(" title=\"" + GetGlobalResources("AllOdds") + "\">");
            sb.append(matchNumTxt);
            sb.append("</a>");
        }
        else {
            sb.append(matchNumTxt);
        }
    }
    return sb.toString();
}

//set the last update time
function setLastUpdateTime(lastUpdateTime) {
    if (!$.isNullOrEmpty(lastUpdateTime)) {
        var date1 = new Date(serverTime);
        var date2 = new Date(lastUpdateTime);
        if (date1 < date2) {
            serverTime = lastUpdateTime;
            $("#spRefreshTime").html(toDateString(date2));
        }
    }
}

function toDateString(d) {
    return padZero(d.getDate()) + '/' + padZero(d.getMonth() + 1) + '/' + d.getFullYear()
        + ' ' + padZero(d.getHours()) + ':' + padZero(d.getMinutes()) + ':' + padZero(d.getSeconds());
}

function toDateStringWithoutSec(d) {
    return padZero(d.getDate()) + '/' + padZero(d.getMonth() + 1) + '/' + d.getFullYear()
        + ' ' + padZero(d.getHours()) + ':' + padZero(d.getMinutes());
}

function padZero(i) {
    return i < 10 ? '0' + i : i;
}

//link to live cast
function callLiveCast(para) {
    MM_openBrWindow(liveCastUrl + para, '', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,top=10,left=0,width=805,height=550');
}

function formatGoal(goalNum) {
    var intGoal = parseInt(goalNum);
    var cntGoal = "";
    if (jsLang == "EN") {
        cntGoal = "<sup>th</sup>";

        if (intGoal < 11 || intGoal > 20) {
            if (intGoal % 10 == 1) {
                cntGoal = "<sup>st</sup>";
            } else if (intGoal % 10 == 2) {
                cntGoal = "<sup>nd</sup>";
            } else if (intGoal % 10 == 3) {
                cntGoal = "<sup>rd</sup>";
            }
        }
        return intGoal + cntGoal + " " + GetGlobalResources("ntslastpart");
    } else {
        return GetGlobalResources("ntsfstpart") + goalNum + GetGlobalResources("ntslastpart");
    }
}

function getMatchTime(_match) {
    var displayTime = -1;
    var status = '';
    var tmpDate = '';
    if (!hasLiveInfo(_match.matchID)) {
        return -1;
    }
    if (_match.liveEvent != null) {
        status = _match.liveEvent.matchstate;
        if (_match.liveEvent.stateTS!='' )
           tmpDate = new Date(_match.liveEvent.stateTS); //yyyy-MM-ddThh:mm:ss+08:00
    }
    if (tmpDate!='') {
        if (status == "FirstHalf" || status == "SecondHalf"
            || status == "FirstExtraTime" || status == "SecondExtraTime") {
            var offset = minutesDiff(tmpDate, new Date(serverTime));
            if (offset < 0) {
                offset = 0;
            }
            if (status == "FirstHalf") {
                displayTime = offset + 0;
            }
            else if (status == "SecondHalf") {
                displayTime = offset + 45;
            }
            else if (status == "FirstExtraTime") {
                displayTime = offset + 90;
            }
            else if (status == "SecondExtraTime") {
                displayTime = offset + 105;
            }
        }
    }
    return displayTime;
}

function formatStatus(_match) { // CMC - to be changed
    var status = _match.liveEvent != null ? _match.liveEvent.matchstate : '';
    var displayTime = getMatchTime(_match);
    var res = "";
    if (status == "FirstHalf" || status == "SecondHalf"
        || status == "FirstExtraTime" || status == "SecondExtraTime") {
        if (isBetRadarIncomplete(_match.matchID) || displayTime == -1) {
            if (status == "FirstHalf") {
                res = GetGlobalResources("IlcFirstHalf");
            } else if (status == "SecondHalf") {
                res = GetGlobalResources("IlcSecondHalf");
            } else if (status == "FirstExtraTime" || status == "SecondExtraTime") {
                res = GetGlobalResources("ET");
            }
        } else {
            var maxTime = 0;
            if (status == "FirstHalf") {
                maxTime = 45;
            } else if (status == "SecondHalf") {
                maxTime = 90;
            } else if (status == "FirstExtraTime") {
                maxTime = 105;
            } else if (status == "SecondExtraTime") {
                maxTime = 120;
            }
            res = formatTime(displayTime, maxTime);
        }
    } else if (status == "HalfTime") {
        res = GetGlobalResources("HT");
    } else if (status == "EndedAfterFT" || status == "EndedAfterET"
        || status == "EndedAfterPK" || status == "BeforeExtraTime") {
        res = GetGlobalResources("FT");
    } else if (status == "ExtraHalfTime") {
        res = GetGlobalResources("ET");
    } else if (status == "BeforePenaltyKick" || status == "PenaltyKick") {
        res = GetGlobalResources("PK");
    }
    return res;
}

function formatTime(displayTime, maxTime) {
    var res = "";
    if (displayTime > maxTime) {
        res = maxTime + "' + "; //res = maxTime + "' + " + (displayTime - maxTime) + "'"
    } else {
        res = displayTime + "'";
    }
    return res;
}

function updateAllMatchesTime() {
    autoRefreshServerTime();

    if (ilcMatches == null) return;
    for (var i = 0; i < ilcMatches.length; i++) {
        for (var j = 0; j < getMatchLength(ilcMatches[i]) ; j++) {
            var m = new Match(ilcMatches[i].matches[j]);
            if (m.IsMatchKickOff() && !isNonInplayAndNoLiveInfoMatch(m))
                updateTime(m.matchIDinofficial);
        }
    }
    setLastUpdateTime(serverTime);
    setTimeout('updateAllMatchesTime()', 60000);
}

function updateTime(matchID) {
    var $matchStatus = $("#" + matchID + "_status");
    if ($matchStatus.length > 0) {
        var displayTime = formatStatus(betValue[matchID]);
        $matchStatus.text(displayTime);
    }
}

function openTips(parentObj, oddsType) {
    if ($("#divTips").length < 1) {
        var tips = "";
        if (oddsType == "fts") {
            tips = GetGlobalResources("Fts", "js");
        } else {
            tips = formatGoal($(parentObj).text());
        }
        var pos = $(parentObj).offset();
        var top = pos.top + $(parentObj).height();
        $("#ilcMatches").append("<div id=\"divTips\">" + tips + "</div>");
        $("#divTips").css({ position: "absolute", top: top, left: pos.left, zIndex: "1000", backgroundColor: "#fff", border: "solid 1px #000", padding: "2px 5px" });
        $(document).oneTime(5000, "goaltips", function () {
            $("#divTips").remove();
            $(document).stopTime("goaltips");
        });
    }
}

function closeTips() {
    $("#divTips").remove();
    $(document).stopTime("goaltips");
}

function minutesDiff(d1, d2) {
    if (!$.isNullOrEmpty(d1) && d1.constructor == Date
        && !$.isNullOrEmpty(d2) && d2.constructor == Date) {
        return Math.floor((d2.getTime() - d1.getTime()) / (1000 * 60));
    }
    return 0;
}

function checkIsVoidMatch(matchStatus) {
    var isVoidMatch = false;
    if (!$.isNullOrEmpty(matchStatus)) {
        //var tmpStatus = matchStatus.split("@")[0].toLowerCase();
        if (matchStatus == "Canceled" || matchStatus == "Abandoned") {
            isVoidMatch = true;
        }
    }
    return isVoidMatch;
}

function checkIsRefundPool(matchPoolStatus) {
    if (!$.isNullOrEmpty(matchPoolStatus) && matchPoolStatus.toUpperCase().indexOf("REFUND") >= 0) {
        return true;
    }
    return false;
}

function getPool(match, oddsType) {
    if (oddsType.toUpperCase() == "FTS/NTS") {
        var newPool;
        var betTypeStr = "ETS";
        var tmpPool = match.etsodds;
        if (tmpPool == null) {
            tmpPool = match.ntsodds;
            if (tmpPool == null) {
                tmpPool = match.ftsodds;
                if (tmpPool != undefined && tmpPool != null)
                    tmpPool.name = "FTS";
                return tmpPool;
            } else {
                betTypeStr = "NTS";
            }
        }

        for (var i = 0; i < tmpPool.length; i++) {
            if (tmpPool[i].POOLSTATUS == "Selling" || tmpPool[i].POOLSTATUS== "NotSelling"
                || tmpPool[i].POOLSTATUS == "FinalStopSell" || tmpPool[i].POOLSTATUS=="Defined") {
               newPool = [tmpPool[i]];
               newPool.name = betTypeStr;
            }
        }
        return newPool;
    }
    else {
        var newPool = match[oddsType.toLowerCase() + "odds"];
        if (newPool != undefined && newPool != null)
            newPool.name = oddsType;
        return newPool;
    }
}

function checkIsSell(pool) {
    var isSell = false;
    if (!$.isNullOrEmpty(pool)) {
        //isSell = pool.isSelling && pool.POOLSTATUS == "Selling";
        if (pool.name == "HAD" || pool.name == "FTS") {
            isSell = (pool.POOLSTATUS == "Selling");
        } else if (pool.name == "ETS" || pool.name == "NTS") {
            isSell = (pool[0].POOLSTATUS == "Selling");
        } else {
            isSell = (pool.POOLSTATUS == "Selling");
        }
    }
    return isSell;
}

function isMatchFinish(m) {
    return m.liveEvent!=null && (m.liveEvent.matchstate.indexOf("Ended") >= 0);
}

function setSelectionCheckBox(chkID, obj) {
    selectionCheckBox[chkID] = obj.checked;
}

function isSelectionCheckBoxChecked(chkID) {
    return selectionCheckBox[chkID] == true;
}

function sortMultipleLines(a, b) {
    if (isMainLineOnTop && a.isMainline)
        return -1;
    if (isMainLineOnTop && b.isMainline)
        return 1;

    var isSplitLineA = a.LINE.indexOf('/') >= 0;
    var lineA = parseFloat(a.line);
    var isSplitLineB = b.LINE.indexOf('/') >= 0;
    var lineB = parseFloat(b.line);

    if (lineA < lineB)
        return -1;
    if (lineA > lineB)
        return 1;

    if (!isSplitLineA && isSplitLineB)
        return -1;
    if (isSplitLineA && !isSplitLineB)
        return 1;
    return 0;
}

function hasMLOddsChange(matchID, pool) {
    for (var i = 0; i < pool.LINELIST.length; i++) {
        if (pool.LINELIST[i].MAINLINE)
            continue;
        var spanID = "#" + matchID + "_" + pool.name + "_H" + ((i > 0) ? '_' + i : "");
        var odds = pool.LINELIST[i].H;
        if (isSelectionCheckBoxChecked(matchID, pool.name, 'H_' + pool.LINELIST[i].LINENUM + '_c')
            && odds.charAt(1) == '1' && oldOdds[spanID] != odds.split('@')[1])
            return true;
        spanID = matchID + "_" + pool.name + "_L" + ((i > 0) ? '_' + i : "");
        odds = pool.LINELIST[i].L;
        if (isSelectionCheckBoxChecked(matchID, pool.name, 'L_' + pool.LINELIST[i].LINENUM + '_c')
            && odds.charAt(1) == '1' && oldOdds[spanID] != odds.split('@')[1])
            return true;
    }
    return false;
}

function checkMainlineChange(matchID, pool) {
    var mainLineNo = 0;
    for (var i = 0; i < pool.LINELIST.length; i++) {
        if (pool.LINELIST[i].MAINLINE) {
            mainLineNo = pool.LINELIST[i].LINENUM;
            break;
        }
    }
    if (oldMainline["m" + matchID] != mainLineNo && multipleLinePoolIds["m" + matchID] != 1) { //reset checkbox
        for (var i = 1; i <= 5; i++) {
            selectionCheckBox[matchID + '_' + pool.name + '_H_' + i + '_c'] = false;
            selectionCheckBox[matchID + '_' + pool.name + '_L_' + i + '_c'] = false;
        }
        oldMainline["m" + matchID] = mainLineNo;
    }
}

function checkCheckboxStatus() {
    for (var key in selectionCheckBox) {
        if (selectionCheckBox[key]) {
            var parts = key.split('_');
            var matchId = parts[0];
            var oddsType = parts[1];
            var item = parts[2];
            var lineNo = parts[3];
            var m = getMatch(matchId);
            if (m == null) {
                selectionCheckBox[key] = false;
                continue;
            }
            var pool = getPool(m, oddsType);
            if (pool == null) {
                selectionCheckBox[key] = false;
                continue;
            }
            if (oddsType == 'HIL' || oddsType == 'CHL') {
                var offered = false;
                for (var i = 0; i < pool.LINELIST.length; i++) {
                    if (pool.LINELIST[i].lineNo == lineNo) {
                        offered = true;
                        break;
                    }
                }
                if (!offered)
                    selectionCheckBox[key] = false;
            }
        }
    }
}

function getNoOfRedCard(_match, _team) {
    var noOfRedCard = 0;
    try {
        if (_match.liveEvent != null
            && _match.liveEvent.liveevent != null && _match.liveEvent.liveevent.length > 0) {
            var eventArr = _match.liveEvent.liveevent;
            for (var k = 0; k < eventArr.length; k++) {
                if ((eventArr[k].actionType == "RedCard" || eventArr[k].actionType == "YellowRedCard")
                    && eventArr[k].homeaway.toLowerCase() == _team) {
                    noOfRedCard++;
                }
            }
            return noOfRedCard;
        }
    } catch (ex) {
    }
    return noOfRedCard;
}

function isNonInplayAndNoLiveInfoMatch(match) {
    return (match.inplayPools == null || match.inplayPools.length == 0) && !hasLiveInfo(match.matchID);
}